﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using System.Reflection;

namespace BYS.XiAnComDept.BussLogic
{
    public class ValidateEntity<T>
    {
        public string ValidateProperty<T>(T entity, string propertyName)
        {
            var propertyInfo = typeof(T).GetProperty(propertyName);
            var value = propertyInfo.GetValue(entity);
            IEnumerable<string> errorInfos =
                  (from va in propertyInfo.GetCustomAttributes(true).OfType<ValidationAttribute>()
                   where !va.IsValid(value)
                   select va.FormatErrorMessage(string.Empty)).ToList();


            if (errorInfos.Count() > 0)
            {
                return errorInfos.FirstOrDefault<string>();
            }
            return null;
        }

    }
}
